import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:logger/logger.dart';
import 'package:my_shop/util/event_bus_util.dart';
import 'package:my_shop/util/event_bus.dart';
import 'package:my_shop/util/logs.dart';
import 'package:network_connectivity_bridge/network_connectivity_bridge.dart';

class NetworkUtil {
  NetworkUtil._internal();

  static final NetworkUtil _instance = NetworkUtil._internal();

  factory NetworkUtil() => _instance;

  static NetworkUtil get instance => _instance;

  bool _isNetAvailable = false;
  bool _initialized = false;

  bool get isNetAvailable => _isNetAvailable;

  /// 初始化监听（只初始化一次）
  Future<void> initialize() async {
    if (_initialized) return;

    await NetworkConnectivityBridge.instance.initialize();
    NetworkConnectivityBridge.instance.onConnectivityChanged
        .listen((List<ConnectivityResult> results) {
      _handleConnectivityResult(results);
    });

    // 初始检测一次网络状态
    final result = await Connectivity().checkConnectivity();
    _handleConnectivityResult(result);

    _initialized = true;
  }

  void _handleConnectivityResult(List<ConnectivityResult> results) {
    printLog('♻️ 网络连接状态：$results', Level.info);

    if (results.contains(ConnectivityResult.none)) {
      _refreshNetState(false);
      return;
    }

    if (results.any((e) =>
    e == ConnectivityResult.mobile ||
        e == ConnectivityResult.wifi ||
        e == ConnectivityResult.ethernet)) {
      _refreshNetState(true);
    }

    // 可根据需要处理其他连接类型，如 vpn、bluetooth、other
  }

  void _refreshNetState(bool isAvailable) {
    if (isAvailable != _isNetAvailable) {
      _isNetAvailable = isAvailable;
      HosEventBusUtils.fire(EventBusConstants.refreshNetState);
    }
  }
}
